package jmine.tec.hydra.web.pages.upload.files;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import jmine.tec.hydra.api.HydraSpecification;
import jmine.tec.hydra.dao.HydraSpecificationDAO;
import jmine.tec.hydra.dao.HydraSystemDAO;
import jmine.tec.hydra.domain.HydraSystem;
import jmine.tec.hydra.web.HydraWebMessages;
import jmine.tec.utils.register.Receiver;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BasicDataBeanNotFoundException;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * Contains a list of specifications scheduled registered.
 * 
 * @author icaro.kume
 */
public class IntegrationRecords implements Serializable, Receiver<Integration> {

    private BaseDAOFactory daoFactory;

    private final List<Integration> integrations = new ArrayList<Integration>();

    /**
     * Returns the registered list of specifications.
     * 
     * @return registered list of specifications.
     */
    public List<HydraSpecification> getSpecifications() {
        List<HydraSpecification> specifications = new ArrayList<HydraSpecification>();
        HydraSpecificationDAO dao = this.daoFactory.getDAOByClass(HydraSpecificationDAO.class);
        for (Integration integracao : this.integrations) {
            String system = integracao.getSystem();
            String action = integracao.getAction();
            try {
                specifications.add(dao.findByActionSystem(this.getSystem(system), action));
            } catch (BeanNotFoundException e) {
                throw new BasicDataBeanNotFoundException(HydraWebMessages.SPECIFICATION_FOR_THE_SYSTEM_NOT_FOUND.create(action, system), e);
            }
        }
        return specifications;
    }

    /**
     * @param system mnemonic system
     * @return o {@link HydraSystem}
     * @throws BeanNotFoundException If you can not find this mnemonic system
     */
    private HydraSystem getSystem(String system) throws BeanNotFoundException {
        return this.getSystemDAO().findByNaturalKey(system);
    }

    /**
     * @return o DAO de {@link HydraSystem}
     */
    private HydraSystemDAO getSystemDAO() {
        return this.daoFactory.getDAOByClass(HydraSystemDAO.class);
    }

    /**
     * @param daoFactory the daoFactory to set
     */
    public void setDaoFactory(BaseDAOFactory daoFactory) {
        this.daoFactory = daoFactory;
    }

    /**
     * @param integrations the integracoes to set
     */
    public void setIntegracoes(List<Integration> integrations) {
        this.register(integrations);
    }

    /**
     * {@inheritDoc}
     */
    public void register(Collection<? extends Integration> registers) {
        for (Integration integracao : registers) {
            this.integrations.add(integracao);
        }
    }

}
